﻿using System;
using System.Windows;
using System.Collections.Generic;
using WickedFlame.Core;
using WickedFlame.Core.History;
using WickedFlame.Core.Shapes;

namespace WickedFlame.Util.Actions
{
    public class CutAction
    {
        public void DoAction(DrawingCanvas canvas, Rect rectangle, bool copyToClipboard)
        {
            if (copyToClipboard)
            {
                CopyToClipboardAction cpy = new CopyToClipboardAction();
                cpy.DoAction(canvas, rectangle);
            }

            List<VectorShape> shapes = new List<VectorShape>();

            if (rectangle.Width > 0 && rectangle.Height > 0)
            {
                foreach (VectorShape shape in canvas.SelectedLayer.ShapeList)
                {
                    if (shape is ICutable)
                        if (shape.IntersectsWith(rectangle) ||
                            shape.IsSelected)
                            shapes.Add(shape);
                }
            }
            else
                shapes = new List<VectorShape>(canvas.SelectedLayer.ShapeList.Selection);

            if (shapes.Count > 0)
            {
                CutCommand command = new CutCommand(shapes, canvas.SelectedLayerIndex);

                foreach (VectorShape shape in shapes)
                {
                    bool handled = false;

                    if (shape.IsSelected)
                    {
                        canvas.RemoveShape(shape);
                        handled = true;
                    }
                    if (shape is ICutable && !handled)
                    {
                        ((ICutable)shape).Cut(rectangle);
                    }
                }

                command.SetNewState();
                canvas.PushHistoryCommand(command);

                DrawingCanvas.DrawTrackers();
            }
        }
    }
}
